package com.example.demo.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.Common.Enum.RoleType;
import com.example.demo.Common.Enum.SexType;
import com.example.demo.Entity.Result;
import com.example.demo.Entity.User;
import com.example.demo.Mapper.UserMapper;
import com.google.common.collect.Lists;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;


/**
 * 用户信息表业务处理
 */
@Service
public class UserServiceImp implements UserService {

    @Autowired
    private UserMapper userMapper;


    /** 新增用户 */
    @Override
    public void insertUser(User user) {
        userMapper.insert(user);
    }

    /** 查询用户 */
    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public int deleteById(Integer id){
        return userMapper.deleteById(id);
    }

    @Override
    public void update(User newuser)
    {
        userMapper.insertOrUpdate(newuser);
    }

    @Override
    public Integer testUpdateById(Integer id) {
        User testUser = new User(6,"test","test","test","test", RoleType.admin, SexType.male,"test","test");
        UpdateWrapper<User> wrapper = new UpdateWrapper<User>().eq("id",id);
        return userMapper.update(testUser,wrapper);
    }
    /** 查询用户 */

    @Override
    public User FindUserByName(String name) {
        return userMapper.FindUserByName(name);
    }
    @Override
    public void register(String username,String password){
        User u = FindUserByName(username);
        if(u == null){
            userMapper.add(username,password);
            System.out.println(Result.success());
        }
        else {
            System.out.println(Result.error("用户名已被注册"));
        }

    }

    @Override
    public String FindPasswordByName(String username){
        return userMapper.FindPasswordByName(username);
    }

    //下载路径
    //@Value("${file.path.local}")
    public String uploadDir="D:\\Avatar";
    /** 存储文件 */
    @Override
    public void takeFile(MultipartFile file) throws Exception{
        File dir = new File(uploadDir);
        // File file2 = new File(uploadDir,file.getName());
        if(!dir.exists())
        {
            dir.mkdirs();
        }

        File targetFile = new File(uploadDir, Objects.requireNonNull(file.getOriginalFilename()));
        try (InputStream in = file.getInputStream();
             OutputStream out = new FileOutputStream(targetFile)) {

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }

    }

    /** 存储文件 */
    @Override
    public void downloadImg(String source, String target) throws Exception {
        Path sourcePath = Paths.get(source);
        Path targetPath = Paths.get(target, sourcePath.getFileName().toString());

        if (!Files.exists(sourcePath)) {
            System.out.println("源文件不存在");
            return;
        }

        Files.createDirectories(targetPath.getParent()); // 确保目标目录存在

        try (InputStream in = Files.newInputStream(sourcePath);
             OutputStream out = Files.newOutputStream(targetPath)) {

            byte[] buf = new byte[8192]; // 增加缓冲区大小
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            System.out.println("文件复制成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件复制失败");
        }
    }

    /** 判断文件类型 */
    @Override
    public boolean imageTypeRight(MultipartFile file) {
        // 校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif");
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = null;
        if (originalFilename != null) {
            fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        }
        return imageType.contains(fileSuffix);
    }

    @Override
    public void updatePWD(String newPassword, String username) {
        userMapper.updatePWD(newPassword,username);
    }

}
